<?php
/**
 * 测试结算单API功能
 * 使用方法: php test-bill-api.php
 */

require_once __DIR__ . '/backend/support/bootstrap.php';

use app\model\BillModel;
use app\model\BizPayRecordModel;
use app\model\BizGoodsTicketModel;
use app\model\BizAdminModel;
use app\model\BizModel;

echo "=== 结算单API功能测试 ===\n\n";

// 1. 检查是否有结算单数据
echo "1. 检查结算单数据...\n";
$billCount = BillModel::count();
echo "   结算单总数: {$billCount}\n";

if ($billCount > 0) {
    $bills = BillModel::limit(3)->get();
    foreach ($bills as $bill) {
        echo "   - 结算单 #{$bill->id}: {$bill->money}元, 状态: {$bill->status}, 月份: {$bill->day}\n";
    }
} else {
    echo "   暂无结算单数据\n";
}

echo "\n";

// 2. 检查商家管理员数据
echo "2. 检查商家管理员数据...\n";
$adminCount = BizAdminModel::count();
echo "   商家管理员总数: {$adminCount}\n";

if ($adminCount > 0) {
    $admins = BizAdminModel::limit(3)->get();
    foreach ($admins as $admin) {
        echo "   - 管理员 #{$admin->id}: 用户ID {$admin->user_id}, 商家ID {$admin->biz_id}\n";
    }
} else {
    echo "   暂无商家管理员数据\n";
}

echo "\n";

// 3. 检查支付记录数据
echo "3. 检查支付记录数据...\n";
$payRecordCount = BizPayRecordModel::count();
echo "   支付记录总数: {$payRecordCount}\n";

$billedPayRecords = BizPayRecordModel::where('bill_id', '>', 0)->count();
echo "   已结算支付记录: {$billedPayRecords}\n";

echo "\n";

// 4. 检查核销码数据
echo "4. 检查核销码数据...\n";
$ticketCount = BizGoodsTicketModel::count();
echo "   核销码总数: {$ticketCount}\n";

$billedTickets = BizGoodsTicketModel::where('bill_id', '>', 0)->count();
echo "   已结算核销码: {$billedTickets}\n";

echo "\n";

// 5. 模拟API调用
echo "5. 模拟API调用测试...\n";

// 获取一个商家管理员
$admin = BizAdminModel::first();
if ($admin) {
    echo "   使用商家管理员: 用户ID {$admin->user_id}, 商家ID {$admin->biz_id}\n";
    
    // 获取该管理员管理的商家的结算单
    $bizIds = BizAdminModel::where('user_id', $admin->user_id)->pluck('biz_id')->toArray();
    echo "   管理的商家ID: " . implode(', ', $bizIds) . "\n";
    
    $bills = BillModel::whereIn('biz_id', $bizIds)->limit(5)->get();
    echo "   该管理员的结算单数量: " . $bills->count() . "\n";
    
    if ($bills->count() > 0) {
        $bill = $bills->first();
        echo "   示例结算单 #{$bill->id}:\n";
        echo "   - 金额: {$bill->money}元\n";
        echo "   - 月份: {$bill->day}\n";
        echo "   - 状态: {$bill->status}\n";
        
        // 获取关联的支付记录
        $payRecords = BizPayRecordModel::where('bill_id', $bill->id)->get();
        echo "   - 关联支付记录: " . $payRecords->count() . "笔\n";
        
        // 获取关联的核销码
        $tickets = BizGoodsTicketModel::where('bill_id', $bill->id)->get();
        echo "   - 关联核销码: " . $tickets->count() . "笔\n";
    }
} else {
    echo "   未找到商家管理员数据\n";
}

echo "\n=== 测试完成 ===\n"; 